package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SecurityUserDetailsService implements UserDetailsService {
	// 模拟数据库的用户记录，如下User类是health_common中的自定义实体类User
	// 修改Role、Permission，为其增加不带参、带参构造方法
	private static Map<String, User> userDb = new HashMap();

	@Reference
	private UserService userService;
	/**
	 * 验证用户名和密码
	 * @param username
	 * @return
	 * @throws UsernameNotFoundException
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 模拟从数据库读取用户信息

		User user = userService.findByUsername(username);

		if(null == user){
			throw new UsernameNotFoundException("用户不存在");
		}


		String userName = user.getUsername();
		String password =user.getPassword();
		// 获取用户角色及权限
		Collection<GrantedAuthority> authList = new ArrayList<>();
		for(Role role:user.getRoles()){
			// 角色关键词
			authList.add(new SimpleGrantedAuthority(role.getKeyword()));
			for (Permission permission:role.getPermissions()){
				// 权限关键词
				authList.add(new SimpleGrantedAuthority(permission.getKeyword()));
			}
		}

		return new org.springframework.security.core.userdetails.User(userName,password,authList);
	}
}
